/*
 * @Description: Token加解密 AES-128-CBC-PKcs7
 * @Author: 0001100986/LiuShuai
 * @Date: 2022-04-01 08:23:26
 * @LastEditTime: 2022-05-16 15:38:23
 * @LastEditors: 0001100986/LiuShuai
 */
import CryptoJS from 'crypto-js';

// 十六位十六进制数作为密钥
const SECRET_KEY = CryptoJS.enc.Utf8.parse('U2FsdGVkX189BapdDOMMTZndj8H1bVahoeDdNFg=');
// 十六位十六进制数作为密钥偏移量
const SECRET_IV = CryptoJS.enc.Utf8.parse('UGVkX193gUiMMY7olU8YOLFcB9jz');

// 加密
export function encrypt (data) {
  if (typeof data === 'object') {
    data = JSON.stringify(data);
  }
  const dataHex = CryptoJS.enc.Utf8.parse(data);
  const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
    iv: SECRET_IV,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.ciphertext.toString();
}

export function decrypt (data) {
  const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
  const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
    iv: SECRET_IV,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}
